package com.qxsx.midi.adapter;

import android.app.Activity;
import android.app.AlertDialog;
import android.app.Dialog;
import android.content.Context;
import android.content.Intent;
import android.os.Handler;
import android.util.DisplayMetrics;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.qxsx.midi.R;
import com.qxsx.midi.activity.me.MeKejiantActivity;
import com.qxsx.midi.config.AppContext;
import com.qxsx.midi.model.Order;
import com.qxsx.midi.utils.CustomProgress;
import com.qxsx.midi.utils.MyNet;
import com.qxsx.midi.utils.SPUtils;
import com.qxsx.midi.utils.Tools;
import com.qxsx.midi.utils.callBackJsonArray;
import com.qxsx.midi.utils.callBackNull;
import com.qxsx.midi.view.ZListView.BaseSwipeAdapter;
import com.qxsx.midi.view.ZListView.DragEdge;
import com.qxsx.midi.view.ZListView.ShowMode;
import com.qxsx.midi.view.ZListView.SimpleSwipeListener;
import com.qxsx.midi.view.ZListView.ZSwipeItem;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import java.util.ArrayList;
import java.util.List;

public class MyOrderAdapter extends BaseSwipeAdapter {

    private CustomProgress customProgress;
    Dialog dialog;
    private Context context;
    private Handler handler;
    private ArrayList<Order> arrayList = new ArrayList<>();
    private LayoutInflater listContainer; // 视图容器
    private Activity activity;

    boolean isLeft = true;  //  默认是左边
    String flag;
    String order_id, order_code;
    private int myPosition;

    public MyOrderAdapter(Context context, ArrayList<Order> arrayList, Activity activity, Handler handler) {
        super();
        this.context = context;
        this.handler = handler;
        listContainer = LayoutInflater.from(context); // 创建视图容器并设置上下文
        this.arrayList = arrayList;
        this.activity = activity;
    }

    @Override
    public int getCount() {
        return arrayList.size();
    }

    @Override
    public Object getItem(int position) {
        return arrayList.get(position);
    }

    @Override
    public long getItemId(int position) {
        return position;
    }

    @Override
    public int getSwipeLayoutResourceId(int position) {
        return R.id.swipe_item;
    }

    @Override
    public View generateView(int position, ViewGroup parent) {
        return listContainer.inflate(R.layout.item_order, parent, false);
    }

    @Override
    public void fillValues(final int position, View convertView) {

        final ZSwipeItem swipeItem = (ZSwipeItem) convertView.findViewById(R.id.swipe_item);
        final Order order = arrayList.get(position);
        ViewHolder viewHolder = new ViewHolder();

        viewHolder.tv_name = (TextView) convertView.findViewById(R.id.tv_name);
        viewHolder.tv_price = (TextView) convertView.findViewById(R.id.tv_price);
        viewHolder.tv_desc = (TextView) convertView.findViewById(R.id.tv_desc);
        viewHolder.img_order_icon = (ImageView) convertView.findViewById(R.id.img_order_icon);
        viewHolder.tv_buy = (TextView) convertView.findViewById(R.id.tv_buy);
        if (isLeft) {
            viewHolder.tv_buy.setText("付款");
            viewHolder.tv_buy.setTextSize(14);
            viewHolder.tv_buy.setBackgroundResource(R.drawable.btn_greenround_white_bg);
        } else {
            viewHolder.tv_buy.setText("点击查看");
            viewHolder.tv_buy.setTextSize(14);
            viewHolder.tv_buy.setBackgroundResource(R.color.theme_white);
        }

        viewHolder.tv_name.setText(order.get_name());
        viewHolder.tv_price.setText(order.get_price());
        viewHolder.tv_desc.setText(order.get_desc());
        if (order.getMajor_id().equals("2172405d-17bb-5f40-da92-cf9cc285a980")) {
            viewHolder.img_order_icon.setImageResource(R.mipmap.exam_wait_guitar);
        } else if (order.getMajor_id().equals("cd12a552-95ee-9d9b-1efb-8c302c6b52c2")) {
            viewHolder.img_order_icon.setImageResource(R.mipmap.exam_wait_jazz);
        } else if (order.getMajor_id().equals("5bb9bcb5-88a0-9c85-0a15-39b51c1142be")) {
            viewHolder.img_order_icon.setImageResource(R.mipmap.exam_wait_bass);
        } else if (order.getMajor_id().equals("87b65e6a-72fc-4617-d61b-351a7d080ed7")) {
            viewHolder.img_order_icon.setImageResource(R.mipmap.exam_wait_base);
        }
        if (order.get_type().equals("0")) {
            viewHolder.tv_buy.setVisibility(View.VISIBLE);

        }
        LinearLayout ll = (LinearLayout) convertView.findViewById(R.id.ll);


        convertView.setTag(viewHolder);


        swipeItem.setShowMode(ShowMode.PullOut);
        swipeItem.setDragEdge(DragEdge.Right);


        swipeItem.addSwipeListener(new SimpleSwipeListener() {

            @Override
            public void onOpen(ZSwipeItem layout) {
                myPosition = position;
            }

            @Override
            public void onClose(ZSwipeItem layout) {
                myPosition = position;
            }

            @Override
            public void onStartOpen(ZSwipeItem layout) {
                myPosition = position;
            }

            @Override
            public void onStartClose(ZSwipeItem layout) {
                myPosition = position;
            }

            @Override
            public void onHandRelease(ZSwipeItem layout, float xvel, float yvel) {
                myPosition = position;
            }

            @Override
            public void onUpdate(ZSwipeItem layout, int leftOffset, int topOffset) {
            }
        });


        viewHolder.tv_buy.setOnClickListener(new OnClickListener() {
            @Override
            public void onClick(View v) {


                if (isLeft) {
                    orderr(order.get_matid(), order.get_type(), order.get_name(), order.get_price());
                } else {
                    toPdfDetail(order.get_matid());
                }


            }
        });
        ll.setOnClickListener(new OnClickListener() {

            @Override
            public void onClick(View v) {
                customProgress = CustomProgress.show(activity, "正在删除....", true, null);

                JSONArray array = new JSONArray();
                JSONObject object = new JSONObject();
                try {
                    object.put("order_id", arrayList.get(position).get_id());
                    array.put(object);
                } catch (JSONException e) {
                    e.printStackTrace();
                }
                MyNet.doPostJsonArray("8023", array, new callBackJsonArray() {
                    @Override
                    public void run(Object code, Object message, JSONArray array) {
                        if ("200".equals(code.toString())) {
                            arrayList.remove(position);
                            swipeItem.close(false);
                            notifyDataSetChanged();
                        } else {
                            Log.e("code", code.toString());
                            Log.e("message", message.toString());
                        }
                        customProgress.dismiss();
                    }
                });

            }
        });
    }


    public void AddData(List<Order> list, boolean flag) {
        for (Order order : list) {
            arrayList.add(order);
        }
        isLeft = flag;
        notifyDataSetChanged();
    }

    public void RemoveAll() {
        if (arrayList != null) {
            this.arrayList.clear();
            notifyDataSetChanged();
        }
    }

    /**
     * 订单
     */

    private void orderr(String id, String type, final String name, final String price) {
        customProgress = CustomProgress.show(activity, "请稍后....", true, null);

        JSONObject object = new JSONObject();
        JSONArray array = new JSONArray();
        String user_id = (String) SPUtils.get(AppContext.getContext(), "user_id", "");
        try {

            object.put("material_id", id);
            object.put("type", type);
            object.put("user_id", user_id);
            object.put("price", price);
            array.put(object);
        } catch (JSONException e) {
            e.printStackTrace();
        }
        MyNet.doPostJsonArray("405", array, new callBackJsonArray() {
            @Override
            public void run(Object code, Object message, JSONArray array) {

                if (code.toString().equals("410")){
                    Toast.makeText(activity,"该教材已过期，请重新下单",Toast.LENGTH_SHORT).show();
                    customProgress.dismiss();
                    return;
                }


                try {
                    JSONObject object1 = array.getJSONObject(0);
                    order_id = object1.getString("order_id");
                    order_code = object1.getString("order_code");
                } catch (JSONException e) {
                    e.printStackTrace();
                }
                customProgress.dismiss();
                dialogbuy(name, price);
            }
        });


    }

    /**
     * 支付的dialog
     */
    private void dialogbuy(final String name, final String price) {

        LayoutInflater layout = LayoutInflater.from(AppContext.getContext());
        View view = layout.inflate(R.layout.dialog_buy_item, null);
        dialog = new AlertDialog.Builder(activity).create();
        TextView tv_zhifu = (TextView) view.findViewById(R.id.tv_zhifu);
        TextView tv_weixin = (TextView) view.findViewById(R.id.tv_weixin);

        /**
         * 支付宝支付
         */
        tv_zhifu.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Tools.AliPayInfo info = new Tools.AliPayInfo("迷笛考级", name, price);
                Tools.WeiXinPayInfo info1 = new Tools.WeiXinPayInfo(order_code, (int) (Float.parseFloat(price) * 100),name);
                info.OrderCode = order_code;
                Tools.Pay(info1, info, activity, "支付宝", new callBackNull() {
                            @Override
                            public void run() {
                                flag = "1";
                                wreslust();
                                dialog.dismiss();
                            }
                        }, new callBackNull() {
                            @Override
                            public void run() {
                                flag = "0";
                                wreslust();
                                Toast.makeText(activity, "支付失败", Toast.LENGTH_SHORT).show();
                                dialog.dismiss();
                            }
                        },
                        null
                );
            }
        });
        /**
         * 微信支付
         */
        tv_weixin.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {

                Tools.AliPayInfo info = new Tools.AliPayInfo("迷笛考级", name, price);
                Tools.WeiXinPayInfo info1 = new Tools.WeiXinPayInfo(order_code, (int) (Float.parseFloat(price) * 100),name);
                info.OrderCode = order_code;
                Tools.Pay(info1, info, activity, "微信", new callBackNull() {
                            @Override
                            public void run() {
                                flag = "1";
                                wreslust();
                                dialog.dismiss();
                            }
                        }, new callBackNull() {
                            @Override
                            public void run() {
                                flag = "0";
                                wreslust();
                                Toast.makeText(activity, "支付失败", Toast.LENGTH_SHORT).show();
                                dialog.dismiss();
                            }
                        },
                        null
                );


            }
        });
        TextView tv_clance = (TextView) view.findViewById(R.id.tv_clance);
        tv_clance.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                dialog.dismiss();
            }
        });

        DisplayMetrics dm = new DisplayMetrics();
        activity.getWindowManager().getDefaultDisplay().getMetrics(dm);
        int x = dm.widthPixels;// 屏幕的宽
        int y = dm.heightPixels;// 屏幕的宽
        dialog = new Dialog(activity, R.style.dialog);
        dialog.getWindow().setLayout((int) (x / 2.2), (int) (y / 1.8));
        dialog.show();
        dialog.setContentView(view);
        dialog.setCancelable(false);


    }

    /**
     * 记录支付结果
     */
    private void wreslust() {

        handler.sendEmptyMessage(0);
        customProgress = CustomProgress.show(activity, "请稍后....", true, null);

        JSONObject object = new JSONObject();
        JSONArray array = new JSONArray();

        try {
            object.put("order_id", order_id);
            object.put("flag", flag);
            array.put(object);
        } catch (JSONException e) {
            e.printStackTrace();
        }
        MyNet.doPostJsonArray("404", array, new callBackJsonArray() {
            @Override
            public void run(Object code, Object message, JSONArray array) {
                customProgress.dismiss();
            }
        });


    }

    /**
     * 跳转到查看订单页面
     *
     * @param id
     */
    private void toPdfDetail(String id) {

        JSONObject object = new JSONObject();
        JSONArray array = new JSONArray();

        try {
            object.put("material_id", id);
            array.put(object);
        } catch (JSONException e) {
            e.printStackTrace();
        }

        MyNet.doPostJsonArray("402", array, new callBackJsonArray() {
            @Override
            public void run(Object code, Object message, JSONArray array) {
                if ("200".equals(code.toString())) {
                    try {
                        JSONObject object1 = array.getJSONObject(0);
                        String file_url = object1.getString("file_url");
                        Intent it = new Intent(context, MeKejiantActivity.class);
                        it.putExtra("file_url", file_url);//传递PDF地址
                        context.startActivity(it);
                    } catch (JSONException e) {
                        e.printStackTrace();
                    }

                } else {

                    Log.e("code", code.toString());
                    Log.e("message", message.toString());

                }

            }
        });

    }

    static class ViewHolder {
        ImageView img_order_icon;
        TextView tv_name;
        TextView tv_price;
        TextView tv_desc;
        TextView tv_buy;
    }
}
